# 递归：recursion
# 递归其实就是函数调用自身的过程
import time


def func_a():
    print("recursion")


def func_b():
    func_a()


func_b()  # recursion


def func_c():
    print("recursion")
    # 在函数中调用自己
    func_c()


# 无限递归调用函数c
# func_c()  # RecursionError: maximum recursion depth exceeded while calling a Python object


def func_d(i):
    if i > 0:  # 指定递归的结束条件
        print("recursion")
        i -= 1  # 向着结束条件推进
        # recursion
        func_d(i)


print("=" * 100)
func_d(10)


# 打印 10 次
# recursion


# 求一个正整数的阶乘
# 5! = 5 * 4* 3 * 2 * 1

def factorial_recursion(n):
    if n == 0:
        return 0
    if n == 1:
        return 1
    return n * factorial_recursion(n - 1)


print("=" * 100)
print(factorial_recursion(10))


def factorial_iteration(n):
    if n == 0:
        return 0
    if n == 1:
        return 1
    result = 1
    for i in range(n):
        result = result * (i + 1)
    return result


print("=" * 100)
print(factorial_iteration(5))


def factorial_iteration_2(n):
    result = n
    for i in range(1, n):
        result *= i
    return result


print("=" * 100)
print(factorial_iteration_2(10))


def factorial_recursion_2(n):
    if n == 0:
        return 0
    if n == 1:
        return 1
    return n * factorial_recursion(n - 1)


print("=" * 100)
print(factorial_recursion_2(10))


# 斐波那契数列

def fib_iter(n):
    a = 1
    b = 1
    c = 1
    while n > 2:
        c = a + b
        a = b
        b = c
        n -= 1
    return c


print("=" * 100)
fib_iter_n = 50
start = time.time()
result_iter_n = fib_iter(fib_iter_n)
end = time.time()
print(F"使用迭代的方式生成斐波那契数列的第{fib_iter_n}个元素的耗时为{start - end}秒，得到的结果为{result_iter_n}")


def fib_recur(n):
    if n == 1 or n == 2:
        return 1
    else:
        return fib_recur(n - 1) + fib_recur(n - 2)


print("=" * 100)
fib_n = 50
start = time.time()
result_fib_n = fib_recur(fib_n)
end = time.time()
print(F"使用递归的方式生成斐波那契数列的第{fib_n}个元素的耗时为{start - end}秒，得到的结果为{result_fib_n}")
